/*
 *      net-sim - networkProtocols.IP.Address
 *
 * 		Mask.java
 *
 *      Copyright 23/12/2008 nicolas
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
package networkProtocols.IP.Address;

import exceptions.AddressException;

// TODO: do it "mierda"...
/**
 * The Class Mask.
 */
public class Mask {

  /** mascara de 32 bits, para los and. */
  private Integer Mask;

  /** prefijo para no recalcularlo. */
  private int prefix;


  /**
   * Crea una mascara dado un prefijo de red.
   *
   * @param pref the pref
   *
   * @throws AddressException the address exception
   */
  public Mask(Integer pref) throws AddressException {
    prefix = pref.intValue();
    if(prefix < 0 || prefix > 31) throw new AddressException("Invalid prefix");
    // Mask 0 es un caso especial que se utiliza para indicar default route en tabla de ruteo
    if(prefix==0) {
      Mask = new Integer(0);
    } else {
      Mask = new Integer(0xFFFFFFFF << (32 - prefix));
    }
  }

  /**
   * Equals.
   *
   * @param f the f
   *
   * @return true, if successful
   */
  public boolean equals(Mask f) {
    boolean r = false;
    if(this.Mask.equals(f.Mask)) r = true;
    return r;
  }

  /**
   * To integer mask.
   *
   * @return the integer
   */
  public Integer toIntegerMask() {return Mask;}

  /**
   * To int.
   *
   * @return the int
   */
  public int toInt() {return Mask.intValue();}

  /**
   * To prefix.
   *
   * @return the int
   */
  public int toPrefix() {return prefix;}

  // Devuelve la mascara en formato decimal con puntos
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  public String toString() {
    int y = Mask.intValue();
    int y4 = y & 0x000000ff;
    int y3 = (y >> 8) & 0x000000ff;
    int y2 = (y >> 16) & 0x000000ff;
    int y1 = (y >> 24) & 0x000000ff;
    String yy = y1+"."+ y2+"."+y3+"."+y4;
    return yy;
  }
}



